package com.kiln.juxingqs.fragment.market

import android.os.Bundle
import android.os.Handler
import android.view.View
import client.global.commlib.base.BaseFragment
import client.global.commlib.widget.EmptyLayout
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.github.mikephil.charting.stockChart.dataManage.TimeDataManage
import com.kiln.juxingqs.R
import com.kiln.juxingqs.databinding.FragmentOneDayBinding
import com.kiln.juxingqs.ui.vm.KLineModel
import com.kiln.juxingqs.utils.DateUtils
import com.kiln.juxingqs.utils.cache.ACache
import com.kiln.juxingqs.utils.constant.Constants
import org.json.JSONException
import org.json.JSONObject


/**
 * 分时
 */
class ChartOneDayFragment : BaseFragment<FragmentOneDayBinding, KLineModel>() {

    private var land = false //是否横屏
    var goodsId: String? = null

    //    private var timeShareJson: JSONObject? = null //分时
    private val kTimeData = TimeDataManage()
    private var aCache: ACache? = null

    override fun getViewId(): Int {
        return R.layout.fragment_one_day
    }

    override fun initViewModel(): KLineModel {
        return createViewModel()
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        land = requireArguments().getBoolean("landscape")
        goodsId = requireArguments().getString("goodsId")
    }

    override fun initWidget() {
        super.initWidget()
        binding.chart!!.initChart(land) //初始化
        aCache = ACache.get(requireContext())
        viewModel.kType.value = 0 //分时
        binding.emptyLayout.setOnClickListener {
            viewModel.isOpenTime.value =
                DateUtils.isBelong(viewModel.begin_time, viewModel.end_time)
            viewModel.holeOneDay(goodsId!!, 0)
        }
    }

    override fun initData() {
        super.initData()
        viewModel.callMinute.observe(this, {
            it?.let {
                if (it.isSuccess) {
                    var time_share = GsonUtils.toJson(it.data!!)
                    time_share?.let {

                        /*aCache?.put(Constants.ONE_DAY, time_share)
                        var one_day = aCache?.getAsJSONObject(Constants.ONE_DAY) //判断本地缓存中有没有数据
                        if (one_day != null) {
                            var timeShareJsonCache: JSONObject? = null //分时
                            try {
                                timeShareJsonCache = JSONObject(one_day.toString())
                            } catch (e: JSONException) {
                                e.printStackTrace()
                            }
                            //#原：上证指数代码000001.IDX.SH
                            kTimeData.parseTimeData(timeShareJsonCache, "000001.IDX.HK", 0.0)
                            binding.chart!!.setDataToChart(kTimeData, viewModel.isOpenTime.value!!)
                        }*/

                        var timeShareJson: JSONObject? = null //分时
                        try {
                            timeShareJson = JSONObject(time_share) //m5，测试数据 ChartData.TIMEDATA
                        } catch (e: JSONException) {
                            e.printStackTrace()
                        }
                        //上证指数代码000001.IDX.SH
                        kTimeData.parseTimeData(timeShareJson, "000001.IDX.HK", 0.0)
                        binding.chart.setDataToChart(kTimeData, viewModel.isOpenTime.value!!)
                    }
                    viewModel.callMinute.value = null
                    binding.emptyLayout.visibility = View.GONE

                } else {
                    if (binding.chart.getmData() == null) {
                        binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR
                    }
                }
//                handler.postDelayed(runnable, 5000) //每5秒执行一次runnable. -第一步
            }
        })

        //分时缓存数据
        viewModel.callOneDayCache.observe(this, {
            it?.let {
                LogUtils.i(it + " <<< OneDayCache...")
            }
        })

        /*
        //        ivLand.setOnClickListener(new View.OnClickListener() {
        //            @Override
        //            public void onClick(View v) {
        //                Intent intent = new Intent(getActivity(), StockDetailLandActivity.class);
        //                getActivity().startActivity(intent);
        //            }
        //        });
        //        if (!land) {
        //            ivLand!!.visibility = View.VISIBLE
        //        } else {
        //            ivLand!!.visibility = View.GONE
        //        }
                */

        //非横屏页单击转横屏页
//        if (!land) {
//           binding.chart.getGestureListenerLine().setCoupleClick(CoupleClick {
//               startActivity(Intent(context, StockDetailLandActivity::class.java).apply {
//                   putExtra("goodsId", "${goodsId}")
//               })
//
//            })
//            binding.chart.getGestureListenerBar().setCoupleClick(CoupleClick {
//                startActivity(Intent(context, StockDetailLandActivity::class.java).apply {
//                    putExtra("goodsId", "${goodsId}")
//                })
//            })
//        }
    }

    companion object {
        fun newInstance(land: Boolean, goodsId: String): ChartOneDayFragment? {
            val fragment = ChartOneDayFragment()
            val bundle = Bundle()
            bundle.putBoolean("landscape", land)
            bundle.putString("goodsId", goodsId)
            fragment.arguments = bundle
            return fragment
        }
    }

    val handler = Handler()

    val runnable: Runnable = object : Runnable {
        override fun run() {
//            //要做的事情
            if (DateUtils.isBelong(viewModel.begin_time, viewModel.end_time)) {
                //实时刷新
                viewModel.holeKLineHead(goodsId)
                viewModel.kType.value = 0
                viewModel.isOpenTime.value = true
                viewModel.holeOneDay(goodsId!!, 0)
                LogUtils.i("在${viewModel.begin_time} - ${viewModel.end_time}，时间范围内")
            } else {
//                LogUtils.i("非开盘时间范围内")
                handler.postDelayed(this, 5000) //每5秒执行一次runnable. -第一步
                viewModel.isOpenTime.value = false
            }
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.isOpenTime.value = DateUtils.isBelong(viewModel.begin_time, viewModel.end_time)
        viewModel.holeOneDay(goodsId!!, 0)
        viewModel.holeKLineHead(goodsId)
    }

    override fun onPause() {
        super.onPause()
        handler.removeCallbacks(runnable);
        handler.removeCallbacksAndMessages(null)
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(runnable);
        handler.removeCallbacksAndMessages(null)
    }
}